﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;

namespace LiveLinq.Internal
{
	sealed class WhereQueryResultWithIndex<T>:ObservableCollectionQueryResultBase<T>
	{
		readonly Func<T, int, bool> _predicate;
		
		public WhereQueryResultWithIndex(IEnumerable<T> source, Func<T, int, bool> predicate)
			: base(source)
		{
			_predicate = predicate;
			OnSourceReset();
		}
		
		protected override void OnSourceReset()
		{
			foreach(var item in _attached)
			{
				DetachItem(item);
			}
			
			_attached.Clear();			
			Items.Clear();
			
			int index=0;
			foreach(var item in _source)
			{
				if(_predicate(item,index))
				{
					Items.Add(item);
				}
				AttachItem(item);
				++index;
			}
			
			OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
		}
		
		protected override void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			OnSourceReset();
		}
	}
}
